import logging
import urllib.parse
from typing import Text

import requests
import requests_mock
from requests import Response
from requests.sessions import PreparedRequest


class ApiSession(requests.Session):
    logger = logging.getLogger(__name__)
    # 类内新增字段
    __mock: requests_mock.Mocker

    def __init__(self, base_url):
        self.base_url = base_url
        super().__init__()
        self.__mock = requests_mock.Mocker(
            session=self,
            real_http=True  # 放行不mock的接口
        )
        self.__mock.start()

    def request(self, method: str, url: str | bytes | Text, **kwargs) -> Response:
        url = urllib.parse.urljoin(self.base_url, url)
        return super().request(method, url, **kwargs)

    def send(self, request: PreparedRequest, *, stream=..., verify=..., cert=..., proxies=...,
             allow_redirects: bool = ..., **kwargs) -> Response:
        self.logger.info(f'请求行: >>> {request.method} {request.url}')
        self.logger.info(f'请求头: >>> {request.headers}')
        self.logger.info(f'请求体: >>> {request.body}')
        response = super().send(request, stream=stream, verify=verify, cert=cert, proxies=proxies,
                                allow_redirects=allow_redirects, **kwargs)
        self.logger.info(f'相应行: <<< {response.reason} {response.status_code}')
        self.logger.info(f'相应头: <<< {response.headers}')
        self.logger.debug(f'相应体: <<< {response.text} \n')
        return response

    def add_mock(self, request, response):
        """
        添加mock功能
        :param request: 要mock的预期接口：{'method':'GET','url':'https://www.google.com'}
        :param response: 期望mock接口返回：{'status_code':200,'headers':{"name":"1234"},'text':'欢迎光临'}
        :return:
        """
        self.__mock.request(**request, **response)
